import math
import numpy as np
import os
import librosa


def getdb(x):
    aa = np.log10(x/32767)
    return 20*aa

def get_ground_noise(filename):
    unit_cut = int(44100*0.02) #每0.02秒一个粗粒度单位
    sound,rate = librosa.load(filename,sr=44100)
    sound1 = sound*32767
    sound2 = np.absolute(sound1)
    lengths = sound2.shape[0]
    
    gaps = math.ceil(lengths/unit_cut)*unit_cut - lengths
    tail = np.zeros((gaps,), dtype=float)
    full_body = np.append(sound2,tail)
    
    data_CLD_amp = np.mean(full_body.reshape(-1, unit_cut), axis=1) #获得粗粒度采样值
    data_CLD_db = getdb(data_CLD_amp) #所有的db值(粗粒度)
    length_CLD = data_CLD_amp.shape[0] #粗粒度的长度
    
    cf1 = np.diff(data_CLD_amp)
    data_CLD_cf = np.absolute(cf1)
    
    biggest_amplitude = np.max(data_CLD_amp)
    
    location_flat = np.where(data_CLD_cf>=35)[0]
    
    key_value = biggest_amplitude * 0.1
    location_low = np.where(data_CLD_amp>=key_value)[0]
    
    location_useless = np.where(data_CLD_amp==0)[0]
    
    target_list = np.array(list(set(location_flat)|set(location_low))) #无用数据的位置(人声)
    
    head = np.array([0,]) 
    target_loc_full = np.append(head,target_list)
    target_loc_full.sort()
    
    target_loc_cf1 = np.diff(target_loc_full) #数据大的部分的位置的差分结果
    
    cf_max = np.max(target_loc_cf1)
    max_loc_pool = np.where(target_loc_cf1==cf_max)
    cf_loc_A = max_loc_pool[0] # 找到目标差分位置，即最终部分的开头
    cf_loc_B = cf_loc_A+1
    
    real_num_A = target_loc_full[cf_loc_A][0]
    real_num_B = target_loc_full[cf_loc_B][0]
    
    x = data_CLD_db[real_num_A:real_num_B]
    ground_noise = np.mean(x)+ 17 # 加上经验值的偏置
    
    print("计算平均值，得到底噪结果是[%s]db" % ground_noise)
    # return ground_noise


if __name__== "__main__":
    get_ground_noise('test_02.wav')
    get_ground_noise('test_03.wav')
    get_ground_noise('test_04.wav')
    get_ground_noise('test_05.wav')
    get_ground_noise('test_06.wav')
    get_ground_noise('test_07.wav')
    get_ground_noise('test_08.wav')
    get_ground_noise('test_09.wav')
    